package com.by.yz.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.by.yz.R;
import com.by.yz.activity.SecondCommunity;
import com.by.yz.adapter.TopicItemAdapter;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Community;
import com.by.yz.entity.TopicInfo;
import com.by.yz.loginUtil.CommunityRESTFul;
import com.by.yz.loginUtil.TopicInfoRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * 我想知道的碎片页面
 * @author wwj_748
 *
 */
public class vehicleCommunityFragment extends Fragment implements View.OnClickListener{

	RecyclerView recyclerView;
	private MaterialRefreshLayout materialRefreshLayout;
	List<TopicInfo> topicList=new ArrayList<TopicInfo>();
	List<Community>  communities=new ArrayList<Community>();//社区的分类
	TopicItemAdapter asd;

	TextView huati_count1;
	TextView huati_count2;
	TextView huati_count3;
	TextView huati_count4;

	int pag=0;

	LinearLayout communicaty_menu_item1;
	LinearLayout communicaty_menu_item2;
	LinearLayout communicaty_menu_item3;
	LinearLayout communicaty_menu_item4;
	String [] str={"祝福墙","外科社区","内科社区","中医社区"};
	String [] chToUnicode=new String[4];
	int[] count=new int[4];
	View view;
	IsNetWork isNetWork;
	private LinearLayout no_topic;
	private boolean isNull = false;
	Boolean isFresh;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("社区onCreate","onCreate");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		Log.e("社区onCreateView","onCreateView");
		view = inflater.inflate(R.layout.fragment_community, container, false);
		huati_count1=(TextView) view.findViewById(R.id.huati_count1);
		huati_count2=(TextView) view.findViewById(R.id.huati_count2);
		huati_count3=(TextView) view.findViewById(R.id.huati_count3);
		huati_count4=(TextView) view.findViewById(R.id.huati_count4);
		asd=new TopicItemAdapter(getActivity(),topicList);
		return view;
	}

	@Override
	public void onStart(){
		Log.e("社区onStart","onStart");
		super.onStart();
		if(isNetWork.isNetworkAvailable(getActivity())){
			topicList.clear();
			getcount();
			pag=0;
			init();
			initData();
		}else {
			//无网络连接情况
			new AlertDialog.Builder(getActivity())
					.setTitle("提示!")
					.setIcon(android.R.drawable.ic_dialog_info)
					.setMessage("检测到您还没开启网络，请开启")
					.setNegativeButton("取消", null)
					.setPositiveButton("开启",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									startActivity(new Intent(
											Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
								}
							}).show();
		}
	}

	private void init(){

		Log.e("社区 init","init");
		communicaty_menu_item1 = (LinearLayout) view.findViewById(R.id.communicaty_menu_item1);
		communicaty_menu_item1.setOnClickListener(this);

		communicaty_menu_item2 = (LinearLayout) view.findViewById(R.id.communicaty_menu_item2);
		communicaty_menu_item2.setOnClickListener(this);

		communicaty_menu_item3 = (LinearLayout) view.findViewById(R.id.communicaty_menu_item3);
		communicaty_menu_item3.setOnClickListener(this);

		communicaty_menu_item4 = (LinearLayout) view.findViewById(R.id.communicaty_menu_item4);
		communicaty_menu_item4.setOnClickListener(this);

		recyclerView = (RecyclerView) view.findViewById(R.id.hot_topic_listview);
		recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
		recyclerView.setAdapter(asd);
		recyclerView.addItemDecoration(new TechnologyTeamDividerItemDecoration(this.getActivity(), TechnologyTeamDividerItemDecoration.VERTICAL_LIST));

		materialRefreshLayout = (MaterialRefreshLayout) view.findViewById(R.id.MaterialRefreshLayout);
		materialRefreshLayout.setLoadMore(true);

		no_topic=(LinearLayout)view.findViewById(R.id.no_topic);
	}

	private void initData(){
		Log.e("社区 initData","initData");
		getCommunity();
		getAllTopics();
		initRefresh();

	}
	public void getAllTopics(){
		TopicInfoRESTFul topicInfoRESTFul= new TopicInfoRESTFul();
		topicInfoRESTFul.getTopicInfo(pag, new TopicInfoRESTFul.MyGetCallBack(){
			@Override
			public void error(String error) {
				topicList=null;
			}
			@Override
			public void ok(JSONArray response) throws JSONException {
				TopicInfo topicInfo ;
				pag++;
				try {
					if (response.length() == 0&&isFresh==true) {
						Toast.makeText(getActivity(), "没有可以刷新的数据", Toast.LENGTH_SHORT).show();
					} else if(response.length() != 0&&isFresh==true) {
//						Toast.makeText(getActivity(), "刷新" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
					}else if(response.length() == 0&&isFresh==false){
						Toast.makeText(getActivity(), "没有可以加载的数据", Toast.LENGTH_SHORT).show();
					}else{
//						Toast.makeText(getActivity(), "加载" + response.length() + "条数据", Toast.LENGTH_SHORT).show();
					}
				}catch (Exception e){

				}
				for (int i=0;i<response.length();i++){
					JSONObject jsonObject= response.getJSONObject(i);
					topicInfo= ToJSonObject.jsonToBean(jsonObject.toString(),TopicInfo.class);
					if(topicInfo.getComunity()!=null&&(!topicInfo.getComunity().equals("健康话题"))) {
						topicList.add(topicInfo);
						isNull = true;
					}else if(topicInfo.getComunity().equals("健康话题")){
						isNull = true;
					}
				}
				if(!isNull){
					no_topic.setVisibility(View.VISIBLE);
					materialRefreshLayout.setVisibility(View.GONE);
				}else{
					no_topic.setVisibility(View.GONE);
					materialRefreshLayout.setVisibility(View.VISIBLE);
				}

				asd.notifyDataSetChanged();
			}
		});
	}
	/*刷新与加载*/
	public void initRefresh(){
		Log.e("社区 initRefresh","initRefresh");
		materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
			@Override
			public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
				android.os.Handler handler=new android.os.Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						isFresh=true;
						materialRefreshLayout.finishRefresh();
						getAllTopics();
					}
				},1000);

			}
			@Override
			public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
				android.os.Handler handler=new android.os.Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						isFresh=false;
						getAllTopics();
						/**
						 * 完成加载数据后，调用此方法，要不然刷新的效果不会消失
						 */
						materialRefreshLayout.finishRefreshLoadMore();
					}
				}, 1000);
			}
		});

	}
	/*
	获得社区分类
	 */
	public  void getCommunity(){

		Log.e("社区 getCommunity","getCommunity");
		CommunityRESTFul communityRESTFul=new CommunityRESTFul();
		communityRESTFul.getcommunities(new CommunityRESTFul.CommunityGETCallBack() {
			@Override
			public void ok(JSONArray response) throws JSONException {
				Log.e("sssss",response.toString());
				Community community;
				for (int i=0;i<response.length();i++){
					JSONObject jsonObject= response.getJSONObject(i);
					community= ToJSonObject.jsonToBean(jsonObject.toString(),Community.class);

					communities.add(i,community);
				}
				asd.notifyDataSetChanged();

			}

			@Override
			public void error(String response) {
				communities=null;
			}
		});
	}
	public void getcount(){
		Log.e("社区 getcount","getcount");
		for(int i=0;i<str.length;i++){
			try{
				chToUnicode[i]=URLEncoder.encode(str[i],"UTF-8");//中文转unicode
				Log.e("ylj","社区编码"+chToUnicode[i]);
				final String string=chToUnicode[i];
				TopicInfoRESTFul topicInfoRESTFul=new TopicInfoRESTFul();
				topicInfoRESTFul.getCommunityTopicInfo(string, new TopicInfoRESTFul.MyGetCallBack() {
					@Override
					public void ok(JSONArray response) throws JSONException {
						try {
							String unicodeToCh=URLDecoder.decode(string, "UTF-8");//unicode转中文
							Log.e("ylj","unicodeToCh"+unicodeToCh);
							switch (unicodeToCh){
								case "祝福墙":
									count[0]=response.length();
									huati_count1.setText(String.valueOf(count[0]));
									break;
								case "外科社区":
									count[1]=response.length();
									huati_count2.setText(String.valueOf(count[1]));
									break;
								case "内科社区":
									count[2]=response.length();
									huati_count3.setText(Integer.toString(count[2]));
									break;
								case "中医社区":
									count[3]=response.length();
									huati_count4.setText(Integer.toString(count[3]));
									break;
								default:
									break;
							}
						}catch (UnsupportedEncodingException e){
							e.printStackTrace();
						}

					}

					@Override
					public void error(String error) {
						Log.e("qwqqqq","数字不匹配      "+error);
					}
				});
			}catch (UnsupportedEncodingException e){
				e.printStackTrace();
			}
		}
	}
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
			case R.id.communicaty_menu_item1:
				try {
					Intent intent = new Intent(getActivity(), SecondCommunity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("currentCommunity", communities.get(0));
					intent.putExtras(bundle);
					startActivity(intent);
//				MFGT.startActivity(getActivity(), SecondCommunity.class);
					break;
				}catch (Exception e){
					e.printStackTrace();
				}
			case R.id.communicaty_menu_item2:
				try {
					Intent intent1=new Intent(getActivity(),SecondCommunity.class);
					Bundle bundle1 = new Bundle();
					bundle1.putSerializable("currentCommunity",communities.get(1));
					intent1.putExtra("count",count[1]);
					intent1.putExtras(bundle1);
					startActivity(intent1);
//				MFGT.startActivity(getActivity(), SecondCommunity.class);
					break;
				}catch (Exception e){
					e.printStackTrace();
				}
			case R.id.communicaty_menu_item3:
				try {
					Intent intent2=new Intent(getActivity(),SecondCommunity.class);
					Bundle bundle2 = new Bundle();
					bundle2.putSerializable("currentCommunity",communities.get(2));
					intent2.putExtras(bundle2);
					startActivity(intent2);
//				MFGT.startActivity(getActivity(), SecondCommunity.class);
					break;
				}catch (Exception e){
					e.printStackTrace();
				}
			case R.id.communicaty_menu_item4:
				try {
					Intent intent3=new Intent(getActivity(),SecondCommunity.class);
					Bundle bundle3 = new Bundle();
					bundle3.putSerializable("currentCommunity",communities.get(3));
					intent3.putExtras(bundle3);
					startActivity(intent3);
//				MFGT.startActivity(getActivity(), SecondCommunity.class);
					break;
				}catch (Exception e){
					e.printStackTrace();
				}
			default:
				Toast.makeText(getContext(), "当前社区为空!", Toast.LENGTH_LONG).show();

		}
	}

}

